package com.station.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by nbzl on 2017/8/18.
 */
public class FileUtil {

    private String root="zl";
    private String app="basestation";
    private String img="img";
    public String imgCache= Environment.getExternalStoragePublicDirectory(root + File.separator + app + File.separator + img).getAbsolutePath();

    private static FileUtil fileUtil;

    public static FileUtil getInstance(){
        if(fileUtil==null){
            fileUtil=new FileUtil();
        }
        if(!new File(fileUtil.imgCache).exists()){
            new File(fileUtil.imgCache).mkdirs();
        }
        return fileUtil;
    }

    public File createImg(String imgName){
        File file=new File(imgCache,imgName);
        if(file.exists()){
            file.delete();
        }
        return file;
    }



    public static List<String> stringToArray(File file) {
        Bitmap bit = BitmapFactory.decodeFile(file.getAbsolutePath());
        int count=Integer.parseInt(String.valueOf(file.length()/1024/5));
        //int count = 1;
        String msg = Bitmap2StrByBase64(bit);
        //Static.saveText(msg);
        Log.e("Mytext", count + "<----count-->" + file.length() / 1024 + "----->" + msg.length());
        int item = msg.length() / count;
        if (msg.length() % count > 0) {
            ++item;
        }
        //String[] o=new String[count];
        List<String> mlist = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            if (((i + 1) * item) <= (msg.length())) {
                //o[i]=msg.substring(i*item, (i+1)*item);
                mlist.add(msg.substring(i * item, (i + 1) * item));
            } else {
                //o[i]=msg.substring(i*item, msg.length());
                mlist.add(msg.substring(i * item, msg.length()));
            }

        }
        //base64ToBitmap(mlist);
        return mlist;
    }
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }
}
